package com.kamistoat.meimeistore.seckill.scheduled;

import com.kamistoat.common.runTimeFunc.RunTimeLog;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;

/**
 * 对Redis中的快照进行备份
 */
@Service
public class RedisFlashScheduled {

    @Value("${meimeistoreseckill.redisflash.shellPath}")
    private String shellPath;

    /**
     * 公共接口，防止某些意外情况下的手动备份
     * 同样测试期间改成每3分钟的第10秒进行一次(和秒杀上架间隔开)
     * 可以在配置文件中自定义
     */
//    @Scheduled(cron = "10 0 3 * * ?")  // 每晚3点零10秒
    @Scheduled(cron = "10 0/30 * * * ?")  // 每30分钟的第10秒进行一次
    public void RedisFlashShot() {
        RunTimeLog.printRunTimeLog("Redis备份");
        if (shellPath.equals("None")){
            return;
        }
        try {
            ClassPathResource shellFile = new ClassPathResource(shellPath);
            BufferedReader shellReader = new BufferedReader(new InputStreamReader(shellFile.getInputStream()));
            while(shellReader.ready()){
                String shellLine = shellReader.readLine();
                Process p = Runtime.getRuntime().
                        exec(new String[]{"sh", "-c", shellLine});  //调用Linux的相关命令
                InputStreamReader ir = new InputStreamReader(p.getInputStream());
                LineNumberReader input = new LineNumberReader(ir);      //创建IO管道，准备输出命令执行后的显示内容
                String line;
                while ((line = input.readLine()) != null) {     //按行打印输出内容
                    System.out.println(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
